import {Component, OnInit} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {BladeContainerBase} from '../../../../shared/blade/blade-container-base';
import {BladeData} from '../../../../shared/blade/blade-data';
import {Blade} from '../../../../shared/blade/blade.model';
import {Command} from '../../../../shared/toolbar.service';
import {DialogResult} from '../../../../shared/dialog.service';
import {FactoryService} from '../../../../service/factory.service';
import {Factory} from '../../../../entity/factory.model';
import {FactoryEditComponent} from '../factory-edit/factory-edit.component';
import {ApplicationService} from '../../../../service/application.service';

@Component({
  selector: 'app-factory-list',
  templateUrl: './factory-list.component.html',
  styleUrls: ['./factory-list.component.css']
})
export class FactoryListComponent extends BladeContainerBase<Factory> {
  factorys: Factory[];

  /**
   * 图片基础路径
   *
   * @type {string}
   * @memberof FactoryListComponent
   */
  baseUrl: string;

  constructor(
    private factoryService: FactoryService,
    private applicationService: ApplicationService
  ) {
    super()
  }

  ngOnInit() {

    // var url = this.applicationService.appConfigData.appRestful;
    // var reg = new RegExp(/(\w+):\/\/([^/:]+)(:\d*)?/)
    // var result = url.match(reg);

    this.baseUrl = window.location.origin;
    this.baseUrl = this.baseUrl == 'http://localhost:4200' ? 'http://192.168.15.109:8080' : this.baseUrl;
    this.commands = [
      new Command('add', '添加', 'fa fa-plus', 'setofkey:insert', blade => this.exeAdd(blade), blade => this.canExeAdd(blade)),
      new Command('edit', '编辑', 'fa fa-edit', 'setofkey:update', blade => this.exeEdit(blade), blade => this.canExeEdit(blade)),
      new Command('delete', '删除', 'fa fa-trash-o', 'setofkey:delete', blade => this.exeDelete(blade), blade => this.canDelete(blade))
    ];
    super.ngOnInit();
  }

  /**
   * 初始化数据
   *
   *
   * @memberof TurbstatusListComponent
   */
  initData(): any | Observable<any> | Promise<any> {
    this.factoryService
      .getFactory()
      .then(res => {
        if (res) {
          this.factorys = [...res];
        } else {
          throw new Error('查询失败！')
        }
      })
      .catch(error => this.bladeData.error = error)
      .then(res => this.bladeData.isLoading = false);
  }

  exeAdd(blend: Blade): void {
    let data: BladeData = new BladeData();
    data.id = 'factoryCreate';
    data.title = '厂家信息';
    data.subtitle = '创建一个厂家信息';
    data.isClosingDisabled = false;
    let createKeyBlade = this.bladeService.createBlade(FactoryEditComponent, data, true);
    this.bladeService.showBlade(createKeyBlade, this.currentBlade);
  }

  canExeAdd(blend: Blade): boolean {
    return true;
  }

  exeEdit(blend: Blade): void {
    if (this.currentEntity != undefined) {

      let data: BladeData = new BladeData();
      data.id = 'factoryEdit';
      data.title = this.currentEntity.factoryName;
      let editKeyBlade = this.bladeService.createBlade(FactoryEditComponent, data, false, this.currentEntity);
      this.currentBlade.bladeService.showBlade(editKeyBlade, this.currentBlade);
    }
  }

  canExeEdit(blend?: Blade): boolean {
    return this.currentEntity != null;
  }

  exeDelete(blend: Blade): void {
    let selectedKeys = this.getSelected();
    if (selectedKeys.length > 0) {
      this.dialogService
        .showConfirmationDialog('确认删除', '是否要删除选中项？')
        .subscribe(dialogResult => {
          if (dialogResult == DialogResult.Ok) {
            this.currentBlade.bladeData.isLoading = true;
            this.factoryService.batchDelete(selectedKeys.map(o => o.factoryId))
              .then(res => {
                if (res) {
                  this.refresh(undefined);
                }
              })
              .catch(error => this.bladeData.error = error)
              .then(res => this.bladeData.isLoading = false);
          }
        })
    }
  }

  canDelete(blend?: Blade): boolean {
    return this.getSelected().length > 0;
  }

  /**
   * 单选
   *
   * @param {any} event
   * @param {any} key
   *
   * @memberof DicKeyListComponent
   */
  onItemCheack(event: HTMLInputElement, key: Factory) {
    key.isChecked = event.checked;
  }

  /**
   * 全选/全不选
   *
   * @param {HTMLInputElement} event
   *
   * @memberof DicKeyListComponent
   */
  onAllCheack(event: HTMLInputElement) {
    if (this.factorys.length > 0) {
      for (let i = 0; i < this.factorys.length; i++) {
        this.factorys[i].isChecked = event.checked;
      }
    }
  }

  onSeletedChange(selectedKey: Factory) {
    this.currentEntity = selectedKey
    /* if (this.currentBlade.childrenCanDeactivate()) {
        this.showTurbstatusCheckBlade(selectedKey);
    } */
  }

  /**
   * 展开风机状态列表弹出层
   *
   * @param {TurbStatus} selectedKey
   *
   * @memberof TurbStatusListComponent
   */
  showTurbstatusCheckBlade(selectedKey: Factory) {
    if (this.currentEntity != selectedKey
      || this.bladeService.findBlade('turbstatusCheckBlade') == undefined) {
      let data: BladeData = new BladeData();
      data.id = 'turbstatusCheckBlade';
      data.title = selectedKey.factoryName;
      data.isClosingDisabled = false;
      let turbstatusCheckBlade = this.bladeService.createBlade(FactoryEditComponent, data, false, selectedKey);
      this.bladeService.showBlade(turbstatusCheckBlade, this.currentBlade).then(res => {
        if (res) {
          this.currentEntity = selectedKey;
        }
      });

    }
  }

  /**
   * 获得选中项
   *
   * @returns {Setofkey[]}
   *
   * @memberof DicKeyListComponent
   */
  getSelected(): Factory[] {
    if (!this.factorys) return [];
    if (this.factorys.length > 0) {
      let filter = this.factorys.filter(ref => ref.isChecked)
      return filter == null ? [] : filter;
    }
    return [];
  }

}


// WEBPACK FOOTER //
// ./src/app/module/basic/factory/factory-list/factory-list.component.ts
